import { createElement } from './utils';
import { ConfigStore } from '../storage/configStore';
import type { ApiConfigItem } from '../types/config';
import { createApiConfigEditor } from './apiConfigInlineEditor';

// 初始化数据从本地存储读取
function getApiConfig(): ApiConfigItem[] {
  return ConfigStore.getConfig().apiConfig || [];
}

// 保存数据到本地存储
function setApiConfig(apiConfig: ApiConfigItem[]) {
  const config = ConfigStore.getConfig();
  config.apiConfig = apiConfig;
  ConfigStore.saveConfig(config);
}

function createApiItemRow(item: ApiConfigItem, idx: number): HTMLElement {
  const configItem = createElement('div', {
    className: 'config-item',
  });

  // 构建配置项头部
  const configHeader = createElement('div', {
    className: 'config-header',
  });

  // 开关部分
  const configStatus = createElement('div', {
    className: 'config-status',
  });
  configStatus.innerHTML = `
    <label class="switch">
      <input type="checkbox" class="api-enable" ${item.enabled ? 'checked' : ''} data-idx="${idx}">
      <span class="slider"></span>
    </label>
  `;

  // URL部分
  const configUrls = createElement('div', {
    className: 'config-urls',
  });
  configUrls.innerHTML = `
    <input type="text" placeholder="目标接口地址" value="${item.target || ''}" readonly>
    <span class="arrow">→</span>
    <input type="text" placeholder="替换接口地址" value="${item.replacement || ''}" readonly>
  `;

  // 操作按钮部分
  const configActions = createElement('div', {
    className: 'config-actions',
  });
  configActions.innerHTML = `
    <button class="edit-btn edit-api-btn">编辑</button>
    <button class="delete-btn delete-api-btn">删除</button>
  `;

  // 组装头部
  configHeader.appendChild(configStatus);
  configHeader.appendChild(configUrls);
  configHeader.appendChild(configActions);
  configItem.appendChild(configHeader);

  // 详情部分（默认隐藏）
  const configDetail = createElement('div', {
    className: 'config-detail',
  });

  // 请求参数部分
  if (item.params && Object.keys(item.params).length > 0) {
    const paramsSection = createElement('div', {
      className: 'detail-section',
    });
    paramsSection.innerHTML = `
      <h4>请求参数</h4>
      <div class="param-list">
        ${Object.entries(item.params).map(([key, value]) => `
          <div class="param-item">
            <input type="text" value="${key}" class="param-name" readonly>
            <input type="text" value="${value}" class="param-value" readonly>
          </div>
        `).join('')}
      </div>
    `;
    configDetail.appendChild(paramsSection);
  }

  // 请求头部分
  if (item.headers && Object.keys(item.headers).length > 0) {
    const headersSection = createElement('div', {
      className: 'detail-section',
    });
    headersSection.innerHTML = `
      <h4>请求头</h4>
      <div class="header-list">
        ${Object.entries(item.headers).map(([key, value]) => `
          <div class="header-item">
            <div class="header-status">
              <label class="switch">
                <input type="checkbox" ${value.enabled ? 'checked' : ''} disabled>
                <span class="slider"></span>
              </label>
            </div>
            <input type="text" value="${key}" class="header-name" readonly>
            <input type="text" value="${value.value}" class="header-value" readonly>
          </div>
        `).join('')}
      </div>
    `;
    configDetail.appendChild(headersSection);
  }

  // 请求体部分
  if (item.body) {
    const bodySection = createElement('div', {
      className: 'detail-section',
    });
    bodySection.innerHTML = `
      <h4>请求体</h4>
      <textarea readonly>${item.body}</textarea>
    `;
    configDetail.appendChild(bodySection);
  }

  configItem.appendChild(configDetail);

  // 点击配置项头部时展开/收起详情
  configHeader.addEventListener('click', (e) => {
    // 如果点击的是按钮，不触发展开/收起
    if (
      (e.target as HTMLElement).classList.contains('edit-api-btn') ||
      (e.target as HTMLElement).classList.contains('delete-api-btn') ||
      (e.target as HTMLElement).classList.contains('api-enable') ||
      (e.target as HTMLElement).closest('.switch')
    ) {
      return;
    }
    configDetail.classList.toggle('expanded');
  });

  return configItem;
}

export function renderApiConfigList(container: HTMLElement) {
  let apiConfig = getApiConfig();
  
  // 创建配置列表容器（如果不存在）
  let configList = container.querySelector('.config-list');
  if (!configList) {
    configList = createElement('div', {
      className: 'config-list',
    });
    container.appendChild(configList);
  }

  // 创建或获取添加配置按钮
  let addBtn = container.querySelector('#addApiBtn') as HTMLButtonElement;
  if (!addBtn) {
    addBtn = createElement('button', {
      className: 'add-config-btn',
      attrs: { id: 'addApiBtn' },
    }) as HTMLButtonElement;
    addBtn.textContent = '+ 添加配置';
    container.insertBefore(addBtn, configList);
  }

  // 渲染配置列表
  function renderList() {
    configList!.innerHTML = '';
    if (apiConfig.length === 0) {
      const emptyTip = createElement('div', {
        attrs: {
          style: `
            text-align: center;
            padding: 40px 0;
            color: #9ca3af;
            font-size: 14px;
          `
        },
      });
      emptyTip.textContent = '暂无配置，点击上方按钮添加';
      configList!.appendChild(emptyTip);
    } else {
      apiConfig.forEach((item, idx) => {
        const row = createApiItemRow(item, idx);
        configList!.appendChild(row);
      });
    }
    
    // 重新绑定所有事件
    bindEvents();
    
    // 确保添加按钮可见
    addBtn.style.display = 'block';
  }

  // 绑定所有事件处理函数
  function bindEvents() {
    // 获取所有的编辑按钮，添加事件
    const editButtons = container.querySelectorAll('.edit-api-btn');
    editButtons.forEach((btn, idx) => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        const configItem = (btn as HTMLElement).closest('.config-item') as HTMLElement;
        const editor = createApiConfigEditor({
          mode: 'edit',
          data: apiConfig[idx],
          onSubmit: (item) => {
            apiConfig[idx] = item;
            setApiConfig(apiConfig);
            renderList();
          },
          onCancel: () => {
            renderList();
          }
        });
        configItem.parentNode?.replaceChild(editor, configItem);
      });
    });

    // 获取所有的删除按钮，添加事件
    const deleteButtons = container.querySelectorAll('.delete-api-btn');
    deleteButtons.forEach((btn, idx) => {
      btn.addEventListener('click', (e) => {
        e.stopPropagation();
        if (confirm('确定要删除此配置吗？')) {
          apiConfig.splice(idx, 1);
          setApiConfig(apiConfig);
          renderList();
        }
      });
    });

    // 获取所有的启用/禁用开关，添加事件
    const enableSwitches = container.querySelectorAll('.api-enable');
    enableSwitches.forEach((switchEl) => {
      switchEl.addEventListener('change', (e) => {
        e.stopPropagation();
        const idx = parseInt((e.target as HTMLInputElement).dataset.idx || '0');
        apiConfig[idx].enabled = (e.target as HTMLInputElement).checked;
        setApiConfig(apiConfig);
      });
    });
  }

  // 添加配置按钮事件
  addBtn.addEventListener('click', () => {
    const editor = createApiConfigEditor({
      mode: 'add',
      onSubmit: (item) => {
        apiConfig.push(item);
        setApiConfig(apiConfig);
        renderList();
      },
      onCancel: () => {
        renderList();
      }
    });
    configList!.insertBefore(editor, configList!.firstChild);
    addBtn.style.display = 'none';
  });

  // 初始渲染
  renderList();
} 